<script>
import httpInstance from "@/utils/http";

export default {
  props:{
    item:{
      type: Object,
      require:true
    }
  },
  data() {
    return {
      showComments: false,
      commentText: '',
      replyText: '',
      replyingTo: null,
      replyTarget: null,
      userInfo: JSON.parse(localStorage.getItem('user')) || {
        nickname: '未知用户',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        signature: '这个人很懒，什么都没留下'
      },
      replay:{}
    }
  },
  methods: {
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return date.toLocaleString();
    },
    
    // 切换评论区显示/隐藏
    toggleComments() {
      this.showComments = !this.showComments;
      this.commentText = '';
      this.replyingTo = null;
      
      // 如果打开评论区，并且还没有获取过评论，则获取评论
      if (this.showComments && (!this.item.comments || this.item.comments.length === 0)) {
        this.fetchComments(this.item.id);
      }
    },
    
    // 获取评论
    async fetchComments(newsId) {
      try {
        const response = await httpInstance.get(`/api/comment/${newsId}`);
        
        if (response && response.code === 200) {
          this.$set(this.item, 'comments', response.data);
        } else {
          this.$message.error(response?.msg || '获取评论失败');
        }
      } catch (error) {
        this.$message.error('获取评论失败，请稍后重试');
      }
    },
    
    // 添加评论
    async addComment() {
      // 检查评论内容是否为空
      if (!this.commentText || !this.commentText.trim()) {
        this.$message.warning('请输入评论内容');
        return;
      }
      
      try {
        const commentData = {
          newsId: this.item.id,
          userId:this.userInfo.id,
          content: this.commentText.trim(),
          isRoot: 1,  // 1表示是根评论（一级评论）
          parentId: null,  // 一级评论没有父评论
          likes: 0
        };
        const response = await httpInstance.post('/api/comment/push', commentData);
        
        if (response && response.code === 200) {
          this.$message.success('评论成功');
          this.commentText = '';
          // 重新获取该动态的评论
          this.fetchComments(this.item.id);
        } else {
          this.$message.error(response?.msg || '评论失败');
        }
      } catch (error) {
        this.$message.error('评论失败，请稍后重试');
      }
    },
    
    // 切换回复框
    toggleReply(reply) {
      // 保存当前要回复的对象
      this.replyTarget = reply;
      
      // 获取评论ID (如果是回复，则使用其父评论ID)
      const commentId = reply.parentId || reply.id;
      
      // 切换回复框显示状态
      this.replyingTo = this.replyingTo === commentId ? null : commentId;
      this.replyText = '';
    },
    
    // 添加回复
    async addReply() {
      // 获取要回复的评论ID和用户名
      const commentId = this.replyTarget.parentId || this.replyTarget.id;
      const replyToUsername = this.replyTarget.nickname || this.replyTarget.username;
      
      console.log(`开始添加回复到评论ID=${commentId}，回复用户=${replyToUsername}`);
      
      // 检查回复内容是否为空
      if (!this.replyText || !this.replyText.trim()) {
        console.warn('回复内容为空，取消添加');
        this.$message.warning('请输入回复内容');
        return;
      }
      
      try {
        const replyData = {
          newsId: this.item.id,
          content: this.replyText.trim(),
          isRoot: 0,  // 0表示是回复（二级评论）
          parentId: commentId,  // 二级评论的父评论ID
          replyTo: replyToUsername,
          likes: 0
        };
        console.log('添加回复数据:', replyData);
        console.log('发送请求: POST /api/comment/push');
        const response = await httpInstance.post('/api/comment/push', replyData);
        console.log('添加回复响应数据:', response);
        
        if (response && response.code === 200) {
          console.log('回复添加成功，ID:', response.data);
          this.$message.success('回复成功');
          this.replyText = '';
          this.replyingTo = null;
          this.replyTarget = null;
          // 重新获取该动态的评论
          this.fetchComments(this.item.id);
        } else {
          console.error('添加回复失败，错误信息:', response?.msg);
          this.$message.error(response?.msg || '回复失败');
        }
      } catch (error) {
        console.error('添加回复请求异常:', error);
        this.$message.error('回复失败，请稍后重试');
      }
    },
    
    // 点赞动态
    async likeNews() {
      try {
        const response = await httpInstance.post(`/api/news/like/${this.item.id}`);
        if (response && response.code === 200) {
          this.item.likes++;
        }
      } catch (error) {
        // 错误处理
      }
    },
    
    // 点赞评论
    async likeComment(commentId) {
      try {
        const response = await httpInstance.post(`/api/comment/like/${commentId}`);
        if (response && response.code === 200) {
          const comment = this.item.comments.find(item => item.id == commentId);
          if (comment) {
            comment.likes++;
          }
        }
      } catch (error) {
        // 错误处理
      }
    },
    
    // 点赞回复
    async likeReply(commentId, replyId) {
      try {
        const response = await httpInstance.post(`/api/comment/like/${replyId}`);
        if (response && response.code === 200) {
          const comment = this.item.comments.find(item => item.id == commentId);
          if (comment) {
            const reply = comment.replies.find(item => item.id == replyId);
            if (reply) {
              reply.likes++;
            }
          }
        } else {
          console.error('点赞回复失败，错误信息:', response?.msg);
        }
      } catch (error) {
        console.error('点赞回复请求异常:', error);
      }
    }
  },
  created() {
    // 初始化评论数组，如果不存在
    if (!this.item.comments) {
      this.$set(this.item, 'comments', []);
    }
  }
}
</script>

<template>
  <div class="new_card_box">
    <div class="card-content">
      <div class="user-info">
        <el-avatar :size="48" :src="item.avatar"></el-avatar>
        <div class="user-meta">
          <span class="username">{{ item.nickname }}</span>
          <span class="signature">{{ item.signature }}</span>
          <span class="time">{{ formatTime(item.createTime) }}</span>
        </div>
      </div>
      <div class="message-content">
        {{ item.msg }}
      </div>
      <div class="action-bar">
        <div class="action-item" @click="likeNews">
          <!-- <i class="el-icon-star-off"></i> -->
          <!-- <span>点赞 {{ item.likes }}</span> -->
        </div>
        <div class="action-item" @click="toggleComments">
          <i class="el-icon-chat-dot-round"></i>
          <!-- <span>评论 {{ item.comments ? item.comments.length : 0 }}</span> -->
          <span>评论</span>
        </div>
        <!-- <div class="action-item">
          <i class="el-icon-share"></i>
          <span>分享</span>
        </div> -->
      </div>
      
      <!-- 评论区 -->
      <div class="comments-section" v-if="showComments">
        <!-- 评论输入框 -->
        <div class="comment-input">
          <el-avatar :size="36" :src="userInfo.avatar"></el-avatar>
          <div class="input-wrapper">
            <el-input 
              type="textarea" 
              v-model="commentText" 
              :rows="2" 
              placeholder="写下你的评论..."
              @keyup.enter.native.ctrl="addComment">
            </el-input>
            <div class="comment-actions">
              <el-button type="primary" size="small" @click="addComment">发表评论</el-button>
            </div>
          </div>
        </div>
        
        <!-- 评论列表 -->
        <div class="comments-list">
          <div v-if="!item.comments || item.comments.length === 0" class="no-comments">
            暂无评论，快来发表第一条评论吧！
          </div>
          
          <div v-for="comment in item.comments" :key="comment.id" class="comment-item">
            <div class="comment-avatar">
              <el-avatar :size="36" :src="comment.avatar"></el-avatar>
            </div>
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-username">{{ comment.nickname || comment.username }}</span>
                <span class="comment-time">{{ formatTime(comment.createTime || comment.time) }}</span>
              </div>
              <div class="comment-text">{{ comment.content }}</div>
              <div class="comment-actions">
                <span class="action" @click="likeComment(comment.id)">
                  <i class="el-icon-star-off"></i> {{ comment.likes }}
                </span>
                <span class="action" @click="toggleReply(comment)">
                  <i class="el-icon-chat-line-round"></i> 回复
                </span>
              </div>
              
              <!-- 回复框 -->
              <div class="reply-input" v-if="replyingTo === comment.id">
                <el-input 
                  type="textarea" 
                  v-model="replyText" 
                  :rows="2" 
                  :placeholder="`回复 ${replyTarget ? (replyTarget.nickname || replyTarget.username) : ''}...`"
                  @keyup.enter.native.ctrl="addReply">
                </el-input>
                <div class="reply-actions">
                  <el-button size="mini" @click="replyingTo = null">取消</el-button>
                  <el-button type="primary" size="mini" @click="addReply">回复</el-button>
                </div>
              </div>
              
              <!-- 回复列表 -->
              <div class="replies-list" v-if="comment.replies && comment.replies.length > 0">
                <div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
                  <div class="reply-avatar">
                    <el-avatar :size="30" :src="reply.avatar"></el-avatar>
                  </div>
                  <div class="reply-content">
                    <div class="reply-header">
                      <span class="reply-username">{{ reply.nickname || reply.username }}</span>
                      <span class="reply-to" v-if="reply.replyTo">回复 {{ reply.replyTo }}</span>
                      <span class="reply-time">{{ formatTime(reply.createTime || reply.time) }}</span>
                    </div>
                    <div class="reply-text">{{ reply.content }}</div>
                    <div class="reply-actions">
                      <span class="action" @click="likeReply(comment.id, reply.id)">
                        <i class="el-icon-star-off"></i> {{ reply.likes }}
                      </span>
                      <span class="action" @click="toggleReply(reply)">
                        <i class="el-icon-chat-line-round"></i> 回复
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.new_card_box {
  margin-bottom: 20px;
  border-radius: 12px;
  background-color: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.new_card_box:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.card-content {
  padding: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-meta {
  margin-left: 12px;
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.signature {
  font-size: 13px;
  color: #8c8c8c;
  margin-top: 2px;
  line-height: 1.2;
}

.time {
  font-size: 13px;
  color: #8c8c8c;
  margin-top: 2px;
}

.message-content {
  font-size: 15px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 16px;
  word-break: break-word;
}

.action-bar {
  display: flex;
  justify-content: space-around;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  cursor: pointer;
  padding: 8px 16px;
  border-radius: 20px;
  transition: all 0.2s ease;
}

.action-item:hover {
  color: #1890ff;
  background-color: #f5f5f5;
}

.action-item i {
  font-size: 16px;
}

.action-item span {
  font-size: 14px;
}

.el-avatar {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.el-avatar:hover {
  transform: scale(1.05);
}

/* 评论区样式 */
.comments-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.comment-input {
  display: flex;
  margin-bottom: 20px;
}

.input-wrapper {
  flex: 1;
  margin-left: 12px;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

.comments-list {
  margin-top: 10px;
}

.no-comments {
  text-align: center;
  color: #8c8c8c;
  padding: 20px 0;
  font-size: 14px;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  margin-right: 12px;
}

.comment-content {
  flex: 1;
}

.comment-header {
  margin-bottom: 6px;
}

.comment-username {
  font-weight: 600;
  font-size: 14px;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #8c8c8c;
  margin-left: 8px;
}

.comment-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-actions {
  font-size: 12px;
  color: #8c8c8c;
}

.action {
  margin-right: 16px;
  cursor: pointer;
}

.action:hover {
  color: #1890ff;
}

.reply-input {
  margin: 10px 0;
}

.reply-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  gap: 8px;
}

.replies-list {
  margin-top: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 8px;
}

.reply-item {
  display: flex;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.reply-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.reply-avatar {
  margin-right: 8px;
}

.reply-content {
  flex: 1;
}

.reply-header {
  margin-bottom: 4px;
  font-size: 12px;
}

.reply-username {
  font-weight: 600;
  color: #333;
}

.reply-to {
  color: #1890ff;
  margin-left: 5px;
}

.reply-time {
  color: #8c8c8c;
  margin-left: 8px;
}

.reply-text {
  font-size: 13px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 6px;
}

.reply-actions {
  font-size: 12px;
  color: #8c8c8c;
}
</style>
